package com.smart.community.region.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.region.entity.ZoneDrawing;
import com.smart.community.region.mapper.ZoneDrawingMapper;
import com.smart.community.region.service.IZoneDrawingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分区绘图数据服务实现类
 *
 * @author Wu.Liang
 * @since 2025-01-30
 */
@Slf4j
@Service
public class ZoneDrawingServiceImpl extends ServiceImpl<ZoneDrawingMapper, ZoneDrawing> implements IZoneDrawingService {

    @Override
    public ZoneDrawing getByCommunityId(Long communityId) {
        log.info("根据社区ID查询绘图数据，社区ID: {}", communityId);
        
        LambdaQueryWrapper<ZoneDrawing> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZoneDrawing::getCommunityId, communityId)
                   .eq(ZoneDrawing::getIsCurrent, SystemStatusEnum.ENABLED.getCode())
                   .last("LIMIT 1");
        
        return this.getOne(queryWrapper);
    }

    @Override
    public List<ZoneDrawing> getAllByCommunityId(Long communityId) {
        log.info("根据社区ID查询所有绘图数据，社区ID: {}", communityId);
        
        LambdaQueryWrapper<ZoneDrawing> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZoneDrawing::getCommunityId, communityId)
                   .orderByDesc(ZoneDrawing::getVersion);
        
        return this.list(queryWrapper);
    }

    @Override
    public int updateByCommunityId(Long communityId, ZoneDrawing drawing) {
        log.info("根据社区ID更新绘图数据，社区ID: {}", communityId);
        
        // 先删除旧的当前版本
        LambdaQueryWrapper<ZoneDrawing> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(ZoneDrawing::getCommunityId, communityId)
                    .eq(ZoneDrawing::getIsCurrent, SystemStatusEnum.ENABLED.getCode());
        this.remove(deleteWrapper);
        
        // 插入新版本
        drawing.setCommunityId(communityId);
        drawing.setIsCurrent(SystemStatusEnum.ENABLED.getCode());
        boolean success = this.save(drawing);
        
        return success ? 1 : 0;
    }
}
